$(function() {
	var cartGoods = ''; //本地购物车数据
	var newAddress = ''; //本地存储的新增收货信息
	var userInfo = ''; //用户登录返回信息
	var filesArr = []; //存储附件图片
	var uploadImgs = []; //存储上传的图片
	var returnFileIds = []; //存储返回的图片id
	var checkedNum = 0;
	//初始化方法
	function init() {
		cartGoods = JSON.parse(sessionStorage.getItem("cartGoods")); //本地存储的加入购物车的商品信息
		newAddress = JSON.parse(sessionStorage.getItem("newAddress")); //本地存储的新增收货信息
		console.log(newAddress);
		userInfo = JSON.parse(sessionStorage.getItem("userInfo")); //本地存储的用户信息
		if(userInfo) {
			$('#userName').html("你好，" + userInfo.name);
			var isTongyongAll = 0;
			var disabled = false;

			//根据url判断是否是修改订单
			var isEdit = getUrlParam('editOrder');
			if(isEdit == "true") { //说明需要修改订单
				var details = JSON.parse(sessionStorage.getItem("orderItemDetails")); //获取订单详情
				sessionStorage.setItem("editOrderUuid",details.uuid);
				sessionStorage.setItem("version",details.version);
				console.log(details);
				//新增地址信息显示
				$('.addressInfo').show();
				$('#receiver').html(details.customerName);
				$('#receiverPhone').html(details.customerTelephone);
				$('#receiverAddress').html(details.receiptAddress);
				//本地存储新增地址的详细信息
				var newInfo = JSON.stringify({
					customerName: details.customerName, //收货人姓名
					customerTelephone: details.memberCardNo, //会员电话
					receiptTelephone: details.customerTelephone, //收货电话
					receiptAddress: details.receiptAddress, //收货地址
					designerPhone: details.designerPhone, //设计师电话
					sellCall: details.boothTelephone, //营业员电话
					orderDate: details.orderDate, //订货日期
					paymentCategory: details.paymentCategory, //deposit（定金），full（全款）
					preActivities: details.preActivities, //预选促销活动
					deliveryMode: details.deliveryMode, //配送方式
					appointmentDeliveryDate: details.appointmentDeliveryDate.split(' ')[0], //配送日期
					install: details.install, //是否安装
					gift: details.gift, //赠品
					voucher: details.voucher, //礼券
					remark: details.remark, //备份
					depositNum: details.preDeposit, //定金金额
				})
				sessionStorage.setItem("newAddress", newInfo); //存储收货信息
				newAddress = JSON.parse(sessionStorage.getItem("newAddress")); //本地存储的新增收货信息
				//添加显示商品
				var havedGoods = []; //订单中已经存在的商品
				for(var i = 0; i < details.lines.length; i++) {
					var imgSrc = "../img/defaultImg.png";

					if(details.lines[i].originalPrice == 0) { //如果是通用商品，插入开头的位置
						isTongyongAll++;
						if(details.lines[i].model = null){
							details.lines[i].model = '';
						}
						if(details.lines[i].specification){
							details.lines[i].specification = '';
						}
						$('.shopCartGoodsMain').prepend('<ul class="shopCartGoodsItem">' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><input type="checkbox" name="selectItem" class="selectItem"/></li>' +
							'<li class="col-md-3 col-sm-3 col-xs-3 text-center">' +
							'<dl class="center-block">' +
							'<dt class="fl"><img class="goodsitemImg" src="' + imgSrc + '"/></dt>' +
							'<dd class="fl text-left">' +
							'<p class="f12 codeandname">' + details.lines[i].code + '&nbsp;' + details.lines[i].name + '</p>' +
							'<p class="fc-gray f12">型号：' + details.lines[i].model + '</p>' +
							'<p class="fc-gray f12">规格：' + details.lines[i].specification + '</p>' +
							'</dd>' +
							'</dl>' +
							'</li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center">￥<span class="goodsPrice">' + details.lines[i].originalPrice + '</span></li>' +
							'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
							'<div class="addAndReduce">' +
							'<button class="reduceBtn">-</button><input type="text" name="count" class="count" value="' + details.lines[i].qty + '" /><button class="plusBtn">+</button>' +
							'</div>' +
							'</li>' +
							'<li class="col-md-2 col-sm-2 col-xs-2 text-center"><div class="discountRateBox"><input class="discountRate" type="text" value="100" /><span class="baifenhao">%</span></div></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><div class="discountRateBox"><input class="discountPrice" type="text" value="' + details.lines[i].price + '" /></div></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center fc-red">￥<span class="xiaoji">' + details.lines[i].price * details.lines[i].qty + '</span></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center deleteItem">删除</li>' +
							'</ul>')
					} else {
						$('.shopCartGoodsMain').append('<ul class="shopCartGoodsItem">' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><input type="checkbox" name="selectItem" class="selectItem"/></li>' +
							'<li class="col-md-3 col-sm-3 col-xs-3 text-center">' +
							'<dl class="center-block">' +
							'<dt class="fl"><img class="goodsitemImg" src="' + imgSrc + '"/></dt>' +
							'<dd class="fl text-left">' +
							'<p class="f12 codeandname">' + details.lines[i].code + '&nbsp;' + details.lines[i].name + '</p>' +
							'<p class="fc-gray f12">型号：' + details.lines[i].model + '</p>' +
							'<p class="fc-gray f12">规格：' + details.lines[i].specification + '</p>' +
							'</dd>' +
							'</dl>' +
							'</li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center">￥<span class="goodsPrice">' + details.lines[i].originalPrice + '</span></li>' +
							'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
							'<div class="addAndReduce">' +
							'<button class="reduceBtn">-</button><input type="text" name="count" class="count" value="' + details.lines[i].qty + '" /><button class="plusBtn">+</button>' +
							'</div>' +
							'</li>' +
							'<li class="col-md-2 col-sm-2 col-xs-2 text-center"><div class="discountRateBox"><input class="discountRate" type="text" value="' + (details.lines[i].price/details.lines[i].originalPrice)*100 + '" /><span class="baifenhao">%</span></div></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><div class="discountRateBox"><input class="discountPrice" type="text" value="' + details.lines[i].price + '" /></div></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center fc-red">￥<span class="xiaoji">' + details.lines[i].price * details.lines[i].qty + '</span></li>' +
							'<li class="col-md-1 col-sm-1 col-xs-1 text-center deleteItem">删除</li>' +
							'</ul>')
					}
					var goodItem = {
						name: details.lines[i].name,
						code: details.lines[i].code,
						fileIds: null,
						price: details.lines[i].originalPrice,
						properties: {
							model: details.lines[i].model,
							specification: details.lines[i].specification,
							unit:details.lines[i].unit,
							grade:details.lines[i].grade,
						},
						remark:details.lines[i].remark,
						category:details.lines[i].category,
						uuid:details.lines[i].uuid,
						pdtUuid:details.lines[i].pdtUuid,
					}
					var itemgoods = {
						count: details.lines[i].qty,
						goodsItem: goodItem
					}
					havedGoods.push(itemgoods);
				}
				//将订单中的商品缓存到本地
				sessionStorage.setItem("cartGoods", JSON.stringify(havedGoods));
				cartGoods = JSON.parse(sessionStorage.getItem("cartGoods")); //本地存储的加入购物车的商品信息
				$('#zdzkl').val('100'); //初始化整单折扣率
				//如果全部是通用商品，即价格为0 的商品，不显示整单折扣率
				if(isTongyongAll == havedGoods.length) {
					$('.zdzklBox').hide();
				}
				//如果当前商品是通用商品，则折扣率不可用，只能使用折扣价
				for(var i = 0; i < $('.discountRate').length; i++) {
					if(Number($('.goodsPrice').eq(i).html()) == 0) {
						$('.discountRate').eq(i).prop('disabled', true);
					}
				}

				//如果有附件图片，显示附件图片
				if(details.fileIds) {
					for(var i = 0; i < details.fileIds.length; i++) {
						$.ajax({
							url: baseUrl + "/palmmall-server/rest/media/fileget/" + details.fileIds[i],
							cache: false,
							async: false,
							dataType: 'json', //服务器返回json格式数据
							type: 'get', //HTTP请求类型
							contentType: "application/json",
							timeout: 20000, //超时时间设置为10秒
							success: function(res) {
								if(res.success) {
									$('.uoloadimgBox').append("<img src='" + res.data + "' class='img-thumbnail' style='width:160px;height=160px;'>");
								} else {
									layer.msg(res.message)
								}
							},
							error: function(res) {
								console.log(res);
								layer.msg("网络出错……");
							}
						})
						returnFileIds.push(details.fileIds[i]); //将现有的附件图片的uuid保存
						sessionStorage.setItem("returnFileIds", JSON.stringify(returnFileIds)); //保存返回的filesIds
					}
				}

				selectedAll(); //默认初始化全部选中
				calc();
				saveRate();
				calcTotalPrice();//计算合计
			} else { //不是修改订单，是正常情况加入购物车
				//如果有存储在本地的购物车数据，填充数据
				if(cartGoods) {
					for(var i = 0; i < cartGoods.length; i++) {
						var imgSrc = "../img/defaultImg.png";
						if(!cartGoods[i].goodsItem.properties.model) {
							cartGoods[i].goodsItem.properties.model = '';
						}
						if(!cartGoods[i].goodsItem.properties.specification) {
							cartGoods[i].goodsItem.properties.specification = '';
						}
						if(cartGoods[i].goodsItem.price == null) {
							cartGoods[i].goodsItem.price = 0;
						}
						if(cartGoods[i].goodsItem.price == 0) { //如果是通用商品，插入开头的位置
							isTongyongAll++;
							$('.shopCartGoodsMain').prepend('<ul class="shopCartGoodsItem">' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><input type="checkbox" name="selectItem" class="selectItem"/></li>' +
								'<li class="col-md-3 col-sm-3 col-xs-3 text-center">' +
								'<dl class="center-block">' +
								'<dt class="fl"><img class="goodsitemImg" src="' + imgSrc + '"/></dt>' +
								'<dd class="fl text-left">' +
								'<p class="f12 codeandname">' + cartGoods[i].goodsItem.code + '&nbsp;' + cartGoods[i].goodsItem.name + '</p>' +
								'<p class="fc-gray f12">型号：' + cartGoods[i].goodsItem.properties.model + '</p>' +
								'<p class="fc-gray f12">规格：' + cartGoods[i].goodsItem.properties.specification + '</p>' +
								'</dd>' +
								'</dl>' +
								'</li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center">￥<span class="goodsPrice">' + cartGoods[i].goodsItem.price + '</span></li>' +
								'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
								'<div class="addAndReduce">' +
								'<button class="reduceBtn">-</button><input type="text" name="count" class="count" value="' + cartGoods[i].count + '" /><button class="plusBtn">+</button>' +
								'</div>' +
								'</li>' +
								'<li class="col-md-2 col-sm-2 col-xs-2 text-center"><div class="discountRateBox"><input class="discountRate" type="text" value="100" /><span class="baifenhao">%</span></div></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><div class="discountRateBox"><input class="discountPrice" type="text" value="' + cartGoods[i].goodsItem.price + '" /></div></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center fc-red">￥<span class="xiaoji">' + cartGoods[i].goodsItem.price * cartGoods[i].count + '</span></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center deleteItem">删除</li>' +
								'</ul>')
						} else {
							$('.shopCartGoodsMain').append('<ul class="shopCartGoodsItem">' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><input type="checkbox" name="selectItem" class="selectItem"/></li>' +
								'<li class="col-md-3 col-sm-3 col-xs-3 text-center">' +
								'<dl class="center-block">' +
								'<dt class="fl"><img class="goodsitemImg" src="' + imgSrc + '"/></dt>' +
								'<dd class="fl text-left">' +
								'<p class="f12 codeandname">' + cartGoods[i].goodsItem.code + '&nbsp;' + cartGoods[i].goodsItem.name + '</p>' +
								'<p class="fc-gray f12">型号：' + cartGoods[i].goodsItem.properties.model + '</p>' +
								'<p class="fc-gray f12">规格：' + cartGoods[i].goodsItem.properties.specification + '</p>' +
								'</dd>' +
								'</dl>' +
								'</li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center">￥<span class="goodsPrice">' + cartGoods[i].goodsItem.price + '</span></li>' +
								'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
								'<div class="addAndReduce">' +
								'<button class="reduceBtn">-</button><input type="text" name="count" class="count" value="' + cartGoods[i].count + '" /><button class="plusBtn">+</button>' +
								'</div>' +
								'</li>' +
								'<li class="col-md-2 col-sm-2 col-xs-2 text-center"><div class="discountRateBox"><input class="discountRate" type="text" value="100" /><span class="baifenhao">%</span></div></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><div class="discountRateBox"><input class="discountPrice" type="text" value="' + cartGoods[i].goodsItem.price + '" /></div></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center fc-red">￥<span class="xiaoji">' + cartGoods[i].goodsItem.price * cartGoods[i].count + '</span></li>' +
								'<li class="col-md-1 col-sm-1 col-xs-1 text-center deleteItem">删除</li>' +
								'</ul>')
						}
					}
					getImg(); //获取商品图片
					$('#zdzkl').val('100'); //初始化整单折扣率
					//console.log("新增的地址：" + newAddress);
					//console.log("当前用户信息：" + userInfo);
					//console.log("购物车信息：" + cartGoods);
					//如果全部是通用商品，即价格为0 的商品，不显示整单折扣率
					if(isTongyongAll == cartGoods.length) {
						$('.zdzklBox').hide();
					}
					//如果当前商品是通用商品，则折扣率不可用，只能使用折扣价
					for(var i = 0; i < $('.discountRate').length; i++) {
						if(Number($('.goodsPrice').eq(i).html()) == 0) {
							$('.discountRate').eq(i).prop('disabled', true);
						}
					}
					var rateInfo = JSON.parse(sessionStorage.getItem("rateInfo")); //本地缓存的折扣率
					if(rateInfo) {
//						console.log(rateInfo)
						//				$('#zdzkl').val(rateInfo.zdzklNum);//整单折扣率
						for(var i = 0; i < rateInfo.rateArr.length; i++) {
							if(parseInt(rateInfo.ratePriceArr[i]/(rateInfo.rateArr[i]/100)) == Number($('.goodsPrice').eq(i).html())){
								$('.discountRate').eq(i).val(rateInfo.rateArr[i]);
								$('.discountPrice').eq(i).val(rateInfo.ratePriceArr[i]);
								$('.xiaoji').eq(i).html(rateInfo.xiaojiArr[i]);
							}
						}
						calc();
					}
					calcTotalPrice();//计算合计
				}
				selectedAll(); //默认初始化全部选中
				calc();//计算整单折扣率
				//如果新增地址信息存在，填充信息
				if(newAddress) {
					$('.addressInfo').show();
					$('#receiver').html(newAddress.customerName);
					$('#receiverPhone').html(newAddress.receiptTelephone);
					$('#receiverAddress').html(newAddress.receiptAddress);
				}
				
				var upload = JSON.parse(sessionStorage.getItem("upload")); //获取本地缓存的上传图片信息
				if(upload) {

					filesArr = upload.filesArr;
					uploadImgs = upload.uploadImgs;
					if(upload.filesArr.length > 1) {
						$('.fileBox').hide();
						$('.upload').hide();
						$('.removeBtn').hide();
					} else {
						filesArr[0] = new File([upload.filesArr], 'img', {
							type: "image/jpeg"
						});
						$('.upload').hide();
						$('.removeBtn').hide();
					}
				}
				var returnfileids = JSON.parse(sessionStorage.getItem('returnFileIds'));
				console.log(returnfileids)
				if(returnfileids) {
					//					console.log(returnfileids)
					returnFileIds = returnfileids;
					if(returnFileIds.length > 1) {
						$('.fileBox').hide();
						$('.upload').hide();
						$('.removeBtn').hide();
					} else {
						$('.upload').hide();
						$('.removeBtn').hide();
					}
					for(var i = 0; i < returnfileids.length; i++) {
						$.ajax({
							url: baseUrl + "/palmmall-server/rest/media/fileget/" + returnfileids[i],
							cache: false,
							async: false,
							dataType: 'json', //服务器返回json格式数据
							type: 'get', //HTTP请求类型
							contentType: "application/json",
							timeout: 20000, //超时时间设置为10秒
							success: function(res) {
								if(res.success) {
									$('.uoloadimgBox').append("<img src='" + res.data + "' class='img-thumbnail' style='width:160px;height=160px;'>");
								} else {
									layer.msg(res.message)
									
								}
							},
							error: function(res) {
								console.log(res);
								layer.msg("网络出错……");
							}
						})
					}
				}
			}
		} else {
			window.location.href = "../index.html";
		}
	}
	init();

	//页面跳转前保存当前页面的数据
	function saveRate() {
		var zdzklNum = $('#zdzkl').val(); //整单折扣率的值
		var rateArr = []; //折扣率数组
		var ratePriceArr = []; //折扣价数组
		var xiaojiArr = []; //小计数组
		for(var i = 0; i < $('.discountRate').length; i++) {
			rateArr.push($('.discountRate').eq(i).val());
			ratePriceArr.push($('.discountPrice').eq(i).val());
			xiaojiArr.push(Number($('.xiaoji').eq(i).html()));
		}
		var rateInfo = JSON.stringify({
			zdzklNum: zdzklNum,
			rateArr: rateArr,
			ratePriceArr: ratePriceArr,
			xiaojiArr: xiaojiArr
		})
		sessionStorage.setItem("rateInfo", rateInfo); //本地缓存当前页面的数据
	}
	//跳转到添加收货地址页面
	$('.addAddress').click(function() {
		saveRate();
		setTimeout(function() {
			window.location.href = "addAddress.html";
		}, 100);
	})
	//跳转到修改地址页面
	$('.changeAddress').click(function() {
		saveRate();
		window.location.href = "addAddress.html?edit=true";
	})

	//数量减按钮点击事件
	$('.reduceBtn').click(function() {
		var index = $(this).parent().parent().parent().index();
		var currentNum = parseInt($(this).next().val());
		if($(this).parent().parent().prev().prev().prev().find('input[type="checkbox"]').prop('checked') && currentNum != 1) {
			$('#totalPrice').html((Number($('#totalPrice').html()) - Number($(this).parent().parent().next().next().find('.discountPrice').val())).toFixed(2));
		}
		currentNum--;
		if(currentNum <= 1) {
			currentNum = 1;
		}
		$(this).next().val(currentNum);
		$(this).parent().parent().next().next().next().find('.xiaoji').html((currentNum * $(this).parent().parent().next().next().find('.discountPrice').val()).toFixed(2));
		cartGoods[index].count = currentNum; //每次点击都要更改本地保存的商品数量
		sessionStorage.setItem("cartGoods", JSON.stringify(cartGoods)); //刷新本地缓存
	})
	//数量加按钮点击事件
	$('.plusBtn').click(function() {
		var index = $(this).parent().parent().parent().index();
		var currentNum = parseInt($(this).prev().val());
		if($(this).parent().parent().prev().prev().prev().find('input[type="checkbox"]').prop('checked')) {
			$('#totalPrice').html((Number($('#totalPrice').html()) + Number($(this).parent().parent().next().next().find('.discountPrice').val())).toFixed(2));
		}
		currentNum++;
		$(this).prev().val(currentNum);
		$(this).parent().parent().next().next().next().find('.xiaoji').html((currentNum * $(this).parent().parent().next().next().find('.discountPrice').val()).toFixed(2));
		cartGoods[index].count = currentNum; //每次点击都要更改本地保存的商品数量
		sessionStorage.setItem("cartGoods", JSON.stringify(cartGoods)); //刷新本地缓存
	})
	//直接修改商品数量
	var currentCount = 1; //记录数量修改前的具体数据
	$('.count').focus(function() {
		currentCount = $(this).val();
	})
	$('.count').blur(function() {
//		console.log($(this).val());
		if($(this).val() > 0) {
			if($(this).val() != currentCount) {
				var index = $(this).parent().parent().parent().index();
//				if($(this).parent().parent().prev().prev().prev().find('input[type="checkbox"]').prop('checked')) {
//					$('#totalPrice').html((Number($('#totalPrice').html()) + Number($(this).parent().parent().next().next().find('.discountPrice').val())).toFixed(2));
//				}
				$(this).parent().parent().next().next().next().find('.xiaoji').html(($(this).val() * $(this).parent().parent().next().next().find('.discountPrice').val()).toFixed(2));
				calcTotalPrice();
				cartGoods[index].count = $(this).val(); //每次点击都要更改本地保存的商品数量
				sessionStorage.setItem("cartGoods", JSON.stringify(cartGoods)); //刷新本地缓存
			}
		} else {
			layer.msg("您输入的数量有误，最少一件商品！")
			$(this).val(currentCount);
		}
	})

	/**
	 * 计算整单折扣率
	 * */
	function calc() {
		var priceNum1 = parseInt(0); //折扣价总和
		var priceNum2 = parseInt(0); //原价总和
		var tig = 0;
		for(var i = 0; i < $('.shopCartGoodsItem').length; i++) {
			if($('.shopCartGoodsItem').eq(i).children().find('.selectItem').prop('checked') && $('.shopCartGoodsItem').eq(i).children().find('.discountRate').prop('disabled') == false) {
				priceNum1 += Number($('.shopCartGoodsItem').eq(i).children().find('.discountPrice').val());
				priceNum2 += Number($('.shopCartGoodsItem').eq(i).children().find('.goodsPrice').html());
				tig++;
			}
		}
		//		console.log(priceNum2)
		if(tig != 0) {
			$('#zdzkl').val(((priceNum1 / priceNum2) * 100).toFixed(0));
		}
	}

	//正整数验证
	var reg = /^[1-9]*[1-9][0-9]*$/; //正整数正则表达式
	//折扣率的更改事件
	var currentDiscount = 0; //记录修改前折扣率
	$('.discountRate').focus(function() {
		currentDiscount = $(this).val();
	})
	$('.discountRate').blur(function() {
		if(reg.test($(this).val())) {
			var rate = $(this).val() / 100;
			var oldPrice = Number($(this).parent().parent().next().next().find('.xiaoji').html()); //先记录改动前的价格数
			$(this).parent().parent().next().find('.discountPrice').val((Number($(this).parent().parent().prev().prev().find('.goodsPrice').html()) * rate).toFixed(2));
			$(this).parent().parent().next().next().find('.xiaoji').html(($(this).parent().parent().next().find('.discountPrice').val() * $(this).parent().parent().prev().children('.addAndReduce').find('.count').val()).toFixed(2));
			if($(this).parent().parent().prev().prev().prev().prev().find('input[type="checkbox"]').prop('checked')) {
				$('#totalPrice').html((Number($('#totalPrice').html()) - oldPrice + Number($(this).parent().parent().next().next().find('.xiaoji').html())).toFixed(2)); //先减去旧价格数，再加上新的价格数
			}
			calc();
			saveRate();
		} else {
			layer.msg("您必须输入正整数！");
			$(this).val(currentDiscount);
		}
	})
	//折扣价的更改事件
	var oldDiscountPrice = 0;
	$('.discountPrice').focus(function(){
		oldDiscountPrice = $(this).val();//折扣价获取焦点的时候，获取折扣价
	})
	$('.discountPrice').blur(function() {
		if($(this).val() == ''){
			$(this).val(oldDiscountPrice);
		}
		
		var countNum = $(this).parent().parent().prev().prev().children().find('.count').val();//获取当前商品 的数量
		var rate = ($(this).val() / Number($(this).parent().parent().prev().prev().prev().find('.goodsPrice').html())).toFixed(4) * 100;
		var oldPrice = Number($(this).parent().parent().next().find('.xiaoji').html()); //先记录改动前的小计数
		if(Number($(this).parent().parent().prev().prev().prev().find('.goodsPrice').html()) == 0){
			$(this).parent().parent().prev().find('.discountRate').val(100);
		}else{
			$(this).parent().parent().prev().find('.discountRate').val(rate);
		}
		$(this).parent().parent().next().find('.xiaoji').html(($(this).val()*countNum).toFixed(2));
		if($(this).parent().parent().prev().prev().prev().prev().prev().find('input[type="checkbox"]').prop('checked')) {
			$('#totalPrice').html((Number($('#totalPrice').html()) - oldPrice + Number($(this).parent().parent().next().find('.xiaoji').html())).toFixed(2)); //先减去旧价格数，再加上新的价格数
		}
		calc();
		saveRate();
	})
	//整单折扣的更改事件
	$('#zdzkl').blur(function() {
		var value = $(this).val();
		$('.discountRate').each(function() {
			//只有商品是非通用商品的时候才会更改折扣率
			if(Number($(this).parent().parent().prev().prev().find('.goodsPrice').html() > 0)) {
				$(this).val(value);
				var rate = $(this).val() / 100;
				var oldPrice = Number($(this).parent().parent().next().next().find('.xiaoji').html()); //先记录改动前的价格数
				$(this).parent().parent().next().find('.discountPrice').val((Number($(this).parent().parent().prev().prev().find('.goodsPrice').html()) * rate).toFixed(2));
				$(this).parent().parent().next().next().find('.xiaoji').html(($(this).parent().parent().next().find('.discountPrice').val() * $(this).parent().parent().prev().children('.addAndReduce').find('.count').val()).toFixed(2));
				if($(this).parent().parent().prev().prev().prev().prev().find('input[type="checkbox"]').prop('checked')) {
					$('#totalPrice').html((Number($('#totalPrice').html()) - oldPrice + Number($(this).parent().parent().next().next().find('.xiaoji').html())).toFixed(2)); //先减去旧价格数，再加上新的价格数
				}
			}
		});
		saveRate();
	})

	//checkbox点击事件

	$('.shopCartGoodsMain .selectItem').change(function() {
		var checkedboxlen = $('.shopCartGoodsMain .selectItem').length;
		if($(this).prop('checked')) {
			checkedNum++; //如果选中，记录加1,
			$('#totalPrice').html(Number($('#totalPrice').html()) + Number($(this).parent().next().next().next().next().next().next().find('.xiaoji').html()));
		} else {
			checkedNum--; //如果取消选中，记录减1
			$('#totalPrice').html(Number($('#totalPrice').html()) - Number($(this).parent().next().next().next().next().next().next().find('.xiaoji').html()));
		}
		$('#totalCount').html(checkedNum);
		if(checkedNum == checkedboxlen) {
			$('.selectAll').each(function() {
				$(this).prop('checked', true);
			})
		} else {
			$('.selectAll').each(function() {
				$(this).prop('checked', false);
			})
		}
	});

	/**
	 * 全选中处理函数
	 * */
	function selectedAll() {
		$('.selectAll').each(function() {
			$(this).prop('checked', true);
		})
		$('.shopCartGoodsMain ul input[type="checkbox"]').each(function() {
			$(this).prop('checked', true);
		})
		var totalcount = 0;
		$('.xiaoji').each(function() {
			totalcount++;
		})
		checkedNum = totalcount;
		$('#totalCount').html(checkedNum);
		calcTotalPrice();
	}
	/**
	 * 计算合计
	 * */
	function calcTotalPrice() {
		var totalprice = 0;
		$('.xiaoji').each(function() {
			var index = $(this).index();
			if($('.selectItem').eq(index).prop('checked') == true) {
				totalprice += Number($(this).html());
			}
		})
		$('#totalPrice').html(totalprice);
	}
	//checkbox全选事件
	$('.selectAll').change(function() {
		if($(this).prop('checked')) {
			selectedAll();
			calc();
		} else {
			$('.selectAll').each(function() {
				$(this).prop('checked', false);
			})
			$('.shopCartGoodsMain ul input[type="checkbox"]').each(function() {
				$(this).prop('checked', false);
			})
			checkedNum = 0;
			$('#totalCount').html(0);
			$('#totalPrice').html(0);
		}
	});

	//删除订单事件
	$('.deleteItem').click(function() {
		var index = $(this).parent().index();
		layer.confirm('你确定要删除该商品？', {
			btn: ['确定', '取消'] //按钮
		}, function() {
			var num = index;
			var isEdit = getUrlParam('editOrder');
//			if(Number($('.goodsPrice').eq(index).html()) == 0){
//				for(var i=0; i<cartGoods.length; i++){
//					var reg = new RegExp(cartGoods[i].goodsItem.code);
//					if(reg.test($('.codeandname').eq(index).html())){
//						num = i;
//					}
//				}
//			}
			for(var i=0; i<cartGoods.length; i++){
				var reg = new RegExp(cartGoods[i].goodsItem.code);
				if(reg.test($('.codeandname').eq(index).html())){
//					console.log("进来了")
					num = i;
				}
			}
			cartGoods.splice(num, 1); //修改本地缓存数据，更新缓存
			if(isEdit){
				var details = JSON.parse(sessionStorage.getItem("orderItemDetails")); //获取订单详情
//				console.log(details);
				details.lines.splice(num, 1);
				sessionStorage.setItem("orderItemDetails",JSON.stringify(details));
			}
			$('.shopCartGoodsMain .shopCartGoodsItem').eq(index).empty().remove();
			sessionStorage.setItem('cartGoods', JSON.stringify(cartGoods));
			saveRate();
			layer.closeAll('dialog');
			window.location.reload();
		});
	})
	//全选删除事件
	$('.deleteAll').click(function() {
		var hasSelected = false;
		$('.shopCartGoodsMain ul input[type="checkbox"]').each(function() {
			if($(this).prop('checked') == true) {
				hasSelected = true;
			}
		})
		if(hasSelected == false) {

			if($('shopCartGoodsMain ul').length == 0) {
				layer.msg("已删除！");
				//没有商品但是有上传图片的情况下，删除图片
				sessionStorage.removeItem("upload"); //清楚上传图片缓存
				$('.uoloadimgBox').empty();
				$('.fileBox').show();
				uploadImgs.splice(0, uploadImgs.length);
				filesArr.splice(0, filesArr.length);
				sessionStorage.removeItem("returnFileIds");
			} else {
				layer.msg("请选择商品再执行删操作！");
			}
		} else {
			layer.confirm('你确定要删除选中商品？', {
				btn: ['确定', '取消'] //按钮
			}, function() {
				$('.shopCartGoodsMain ul input[type="checkbox"]').each(function() {
					var index = $(this).parent().parent().index();
					if($(this).prop('checked') == true) {
						$('.shopCartGoodsMain .shopCartGoodsItem').eq(index).empty().remove();
						cartGoods.splice(index, 1); //修改本地缓存数据，更新缓存
						sessionStorage.setItem('cartGoods', JSON.stringify(cartGoods));
					}
				})
				if($('.selectAll').eq(1).prop('checked') == true) {
					sessionStorage.removeItem('rateInfo'); //清楚折扣率缓存
					sessionStorage.removeItem("upload"); //清楚上传图片缓存
					sessionStorage.removeItem("cartGoods"); //清楚缓存商品
					$('.uoloadimgBox').empty();
				} else {
					saveRate();
				}
				layer.closeAll('dialog');
				window.location.reload();
			});
		}
	})

	//为文件上传添加change事件
	var formData;
	var fileM = document.querySelector("#file");

	$("#file").on("change", function() {
		if(fileM.files.length > 0 && fileM.files.length <= 2 && $('.uoloadimgBox img').length < 2) {
			var isJpg = true;
			for(var i = 0; i < fileM.files.length; i++) {
				var reg = new RegExp('.jpg');
				if(!reg.test(fileM.files[i].name)) {
					isJpg = false;
					layer.msg("您只能上传jpg格式图片");
					$("#file").val(''); //将input file置为空
					break;
				}
			}
			if(isJpg) {
				for(var i = 0; i < fileM.files.length; i++) {
					filesArr.push(fileM.files[i]);
					reads(fileM.files[i])
					//获取文件对象，files是文件选取控件的属性，存储的是文件选取控件选取的文件对象，类型是一个数组
					var fileObj = fileM.files[i];
					//创建formdata对象，formData用来存储表单的数据，表单数据时以键值对形式存储的。
					formData = new FormData();
					formData.append('file', fileObj);
					uploadFiles(formData);
				}
				//				console.log(formData)
//				$('.upload').show();
				$('.removeBtn').show();
			}

		} else {
			layer.msg("您最多只能上传两张图片");
		}
	})

	//预览上传图片
	function reads(fil) {
		var reader = new FileReader();
		reader.readAsDataURL(fil);
		reader.onload = function() {
			$('.uoloadimgBox').append("<img src='" + reader.result + "' class='img-thumbnail' style='width:160px;height=160px;'>");
			uploadImgs.push(reader.result);
		};
	}
	//点击图片上传

//	$('#upload').click(function() {
	function uploadFiles(formData){
		var isUploadAll = true;
		console.log(filesArr);

			$.ajax({
				url: baseUrl + "/palmmall-server/rest/media/upload/list",
				cache: false,
				dataType: 'json', //服务器返回json格式数据
				data: formData,
				type: 'post', //HTTP请求类型
				processData: false, //processData用于对data参数进行序列化处理，默认值是true。默认情况下发送的数据将被转换为对象，如果不希望把File转换，需要设置为false
				contentType: "multipart/form-data",
				timeout: 10000, //超时时间设置为10秒；
				async: true,
				success: function(res) {
//					console.log(res);
					if(res.success == true) {
						returnFileIds.push(res.data[0].id);
						sessionStorage.setItem("returnFileIds", JSON.stringify(returnFileIds)); //保存返回的filesIds
						if($('.uoloadimgBox img').length < 2) {
//							$('.upload').hide();
//							$('.removeBtn').hide();
						} else {
							$('.fileBox').hide();
							$('.removeBtn').hide();
						}
					} else {
						isUploadAll = false;
						layer.msg(res.message);
					}
				},
				error: function(res) {
					isUploadAll = false;
					layer.msg("网络出错……")
				}
			});
		if(isUploadAll) {
			var upload = JSON.stringify({
				filesArr: filesArr,
				uploadImgs: uploadImgs
			})
			sessionStorage.setItem("upload", upload); //上传成功，本地缓存上传的图片
			layer.msg("上传成功");
		}
	}
	//取消上传图片
	$('#removeBtn').click(function() {
		filesArr.splice(0, filesArr.length); //删除上传图片，清空files数组
		$('.uoloadimgBox').empty(); //清空视图
		$("#file").val('');
		$('.upload').hide();
		$('.removeBtn').hide();
		uploadImgs.splice(0, uploadImgs.length); //清楚uploadImgs中的数据
		sessionStorage.removeItem('upload'); //清空本地缓存上传图片
		sessionStorage.removeItem('returnFileIds');
		returnFileIds.splice(0, returnFileIds.length);
	})
	//生成订单按钮点击事件
	$('#generateOrderBtn').click(function() {
		if(Number($('#totalCount').html()) == 0) {
			layer.alert('请选择商品', {
				icon: 6
			});
		} else {
			if(newAddress) {
				var isgo = true;
				if(newAddress.paymentCategory == "deposit") {
					if(newAddress.depositNum <= 0 || newAddress.depositNum > Number($('#totalPrice').html())) {
						isgo = false;
						layer.alert('您的定金不能为0或者大于当前总金额，请确认定金。', {
							icon: 6
						});
					}
				}
				if(isgo) {
					layer.load(0, {
						shade: 0.5
					});
					var lines = []; //商品详情数组
					for(var i = 0; i < cartGoods.length; i++) {
						var index = i;
						var reg = new RegExp(cartGoods[i].goodsItem.code);
						for(var j=0; j<$('.codeandname').length; j++){
							if(reg.test($('.codeandname').eq(j).html())){//便利当前购物车的商品，如果商品code相同，获取当前相同code的商品的索引
							index = j;
							}
						}
						var item = {
							model: cartGoods[i].goodsItem.properties.model,
							remark: cartGoods[i].goodsItem.remark,
							qty: cartGoods[i].count, //商品数量？
							code: cartGoods[i].goodsItem.code,
							unit: cartGoods[i].goodsItem.properties.unit,
							category: {
								uuid: cartGoods[i].goodsItem.category.uuid,
								name: cartGoods[i].goodsItem.category.name,
								code: cartGoods[i].goodsItem.category.code
							},
							price: $('.discountPrice').eq(index).val(),
							originalPrice: cartGoods[i].goodsItem.price,
							name: cartGoods[i].goodsItem.name,
							specification: cartGoods[i].goodsItem.properties.specification,
							grade: cartGoods[i].goodsItem.properties.grade,
							stdTotal: Number($('.xiaoji').eq(index).html()),
							pdtUuid: cartGoods[i].goodsItem.uuid, //产品uuid?
							uuid: null
						}
						if($('.selectItem').eq(i).prop('checked') == true) {
							lines.push(item);
						}

					}
					//				if(returnFileIds.length == 0){
					//					returnFileIds = null;
					//				}
					var editOrderUuid = sessionStorage.getItem("editOrderUuid");
					if(!editOrderUuid){
						editOrderUuid = null;
					}
					var version = sessionStorage.getItem("version");
					if(!version){
						version = null;
					}
					
					//修改需要传递的预约活动的值，只专活动名和uuid
					var currentPreActivity = [];
					if(newAddress.preActivities && $.isArray(newAddress.preActivities)){
						for(var i=0; i<newAddress.preActivities.length; i++){
							var item = {
								activityName:newAddress.preActivities[i].activityName,
								promotionUuid:newAddress.preActivities[i].promotionUuid
							}
							currentPreActivity.push(item);
						}
					}else{
						currentPreActivity = null;
					}
					
					var postData = {
						install: newAddress.install,
						receiptAddress: newAddress.receiptAddress,
						customerName: newAddress.customerName,
						gift: newAddress.gift,
						bizState: "ineffect",
						store: {
							uuid: userInfo.stores[0].uuid,
							name: userInfo.stores[0].name,
							code: userInfo.stores[0].code
						},
						remark: newAddress.remark,
						contract: {
							uuid: userInfo.stores[0].contracts[0].uuid,
							name: userInfo.stores[0].contracts[0].name,
							code: userInfo.stores[0].contracts[0].code
						},
						boothTelephone: newAddress.sellCall, //营业员电话
						boothNumber: userInfo.stores[0].contracts[0].positions[0].code,
						paymentCategory: newAddress.paymentCategory,
						orderDate: newAddress.orderDate,
						deliveryMode: newAddress.deliveryMode,
						appointmentDeliveryDate: newAddress.appointmentDeliveryDate + " 00:00:00",
						preActivities: currentPreActivity,
						customerTelephone: newAddress.receiptTelephone, //收货电话
						fileIds: returnFileIds, //上传图片返回id
						tenant: {
							uuid: userInfo.tenant.uuid,
							name: userInfo.tenant.name,
							code: userInfo.tenant.code
						},
						memberCardNo: newAddress.customerTelephone, //会员电话
						designerName: null,
						designerPhone: newAddress.designerPhone,
						lines: lines,
						preDeposit: newAddress.depositNum,
						voucher: newAddress.voucher,
						uuid:editOrderUuid,//修改订单传入的uuid
						version:version,
					}
//					console.log(postData)
					var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
					var operId = userInfo.code;
					var operName = encodeURI(userInfo.name);
					generateOrder(postData, time, operId, operName); //调用接口函数
				}

			} else {
				layer.msg("请添加收货地址");
			}

		}
	})
})